/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.semi.fw;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;



/**
 *
 * @author liaoyq
 */
public class SocketWrapper { 
   // private static Charset charset  =  Charset.forName( "gb2312" );
   // private static  CharsetDecoder decoder = charset.newDecoder();  
    private SocketChannel chennel ;    
    protected SelectionKey mKey = null;

    public SocketWrapper(SocketChannel sc){
        chennel  = sc;
    }      
    public boolean  noValidate(){
        return ( (!chennel.isOpen())||chennel.socket().isClosed()|| (!chennel.isConnected()) );
    }
    public  boolean isValidate(){
        return chennel.isOpen() && chennel.isConnected() &&(!chennel.socket().isClosed());
    }
    public String remoteAddr(){
        return chennel.socket().getRemoteSocketAddress().toString();
    }    
    /*
    public void configureBlocking() throws SocketException{        
        chennel.socket().setTcpNoDelay(true);
        chennel.socket().setSoTimeout(20);
        chennel.socket().setSoLinger(true, 20);         
    }     
*/
    public void close(){
        if( chennel!=null ) try {
            chennel.close();
        } catch (IOException ex) {
        }
        chennel = null;
    }
    public void write(String data ) throws IOException{
        ByteBuffer re = ByteBuffer.wrap(data.getBytes());
        chennel.write(re);
    }
    public void write(byte[] data ) throws IOException{
        ByteBuffer re = ByteBuffer.wrap(data);
        chennel.write(re);
    }    
    public String readBlock(ByteBuffer sc) throws IOException{
        sc.clear();
       int count = chennel.read(sc);
       if( count<0 ) return null;
       if( count==0 ) return "";
        // 切换buffer到读状态,内部指针归位.
        sc.flip();
        //CharBuffer b = decoder.decode(sc);
        //return b.toString();    
        return new String(sc.array(),0,count);
    }
    public String read(ByteBuffer sc) throws IOException{
        sc.clear();
        int count = chennel.read(sc);
        if (count <= 0)  return null; // 客户端已经断开连接.
        // 切换buffer到读状态,内部指针归位.
        sc.flip();
        //CharBuffer b = decoder.decode(sc);
        //return b.toString();
        return new String(sc.array(),count);
    } 
}
